#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/alias.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_run.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/print_sys_info.sh"

# APP_INSTALL_NAME="step-audio-editx"
APP_TARGET_DIR_NAME="step-audio-editx"

export CURRENT_APP_PATH="$LMD_APPS_DIR/$APP_TARGET_DIR_NAME"
echo "App Dir: ${CURRENT_APP_PATH}"

cd "$CURRENT_APP_PATH"

if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

export GRADIO_TEMP_DIR="$CURRENT_APP_PATH/temp"
CONDA_PREFIX="./venv"

# if [ "$LMD_LAUNCH_APP_OPT_USE_GPU" = "false" ]; then
#   export CUDA_VISIBLE_DEVICES="-1"
# fi

# echo "CUDA_VISIBLE_DEVICES $CUDA_VISIBLE_DEVICES"

QUANTIZATION_PARAMS=""
if [ -n "$LMD_LAUNCH_APP_MODULE" ]; then
  echo "LMD_LAUNCH_APP_MODULE $LMD_LAUNCH_APP_MODULE"
else 
  echo "set default LMD_LAUNCH_APP_MODULE: int4"
  LMD_LAUNCH_APP_MODULE="int4"
fi

if [ "$LMD_LAUNCH_APP_MODULE" = "non-quantized" ]; then
  QUANTIZATION_PARAMS=""
else
  QUANTIZATION_PARAMS="--quantization $LMD_LAUNCH_APP_MODULE"
fi

APP_FILE="app.py"

export XDG_CACHE_HOME="${CURRENT_APP_PATH}/XDG_CACHE_HOME"
export XDG_CONFIG_HOME="${CURRENT_APP_PATH}/XDG_CONFIG_HOME"
export XDG_DATA_HOME="${CURRENT_APP_PATH}/XDG_DATA_HOME"
export XDG_STATE_HOME="${CURRENT_APP_PATH}/XDG_STATE_HOME"

export HF_HOME="$CURRENT_APP_PATH/tmp_hf_home"

PORT_PARAM=""
if [ -n "$GRADIO_SERVER_PORT" ]; then
  PORT_PARAM="--server-port $GRADIO_SERVER_PORT"
fi

conda run -p $CONDA_PREFIX --no-capture-output python "$APP_FILE" --model-path "models" --model-source local $QUANTIZATION_PARAMS $PORT_PARAM

